// pages/home/home.js
const config = require('../../config')
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()
import {store} from '../../store/store'
const {replaceBaseUrl} =  require('../../utils/util')
import Toast from '@vant/weapp/toast/toast';
import { BASE_URL, PIC_URL } from '../../config'
let timer = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    store,
    isFalse: false,
    display: false,
    swiperList: [],
    noticeText: "重要通知：小程序将于2025年6月25日正式上线",
    animationData: {},
    categories: "有害垃圾",
    gridList: [
    ],
    recorderTapping: false,
    picRecordRes: [
      {item: '手机', score: '90%', category: 1},
      {item: '充电器', score: '60%', category: 2},
      {item: '鼠标', score: '55%', category: 0},
      {item: '手表', score: '40%', category: 3}
    ],
    category: [
      '可回收物',
      '有害垃圾',
      '厨余垃圾',
      '其他垃圾'
    ],
    show: false,
    content: ''
  },
  goToDetail(e) {
    console.log(e);
    wx.navigateTo({
      url: `/pkg/pages/articleDetail/articleDetail?id=${e.currentTarget.dataset.id}`,
    })
  },
  async _getSwperList() {
    const token = wx.getStorageSync('token')
    const {data: res} = await wx.p.request({
      url: BASE_URL + '/article/slideshow',
      header: {
        token: token
      }
    })
    res.data.forEach(element => {
      element.image = replaceBaseUrl(PIC_URL, element.image)
    });
    console.log(res.data);
    this.setData({
      swiperList: res.data
    })
  },
  picRecord() {
    // 打开结果展示栏
    const that = this
    const token = wx.getStorageSync('token')
    wx.chooseMedia({
      count: 1, // 默认9
      mediaType: ['image'],
      sourceType: ['album', 'camera'], // 相册和相机
      camera: 'back', // 使用后置摄像头
      success(res) {
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        });
        const tempFilePaths = res.tempFiles[0].tempFilePath
        // tempFilePath可以作为img标签的src显示图片
        // 或者上传到服务器进行识别
        console.log('图片临时路径:', tempFilePaths)
        timer = setTimeout(() => {
          Toast.clear()
          that.setData({
            isFalse: true
          })
          clearTimeout(timer)
        }, 35000)
        wx.uploadFile({
          filePath: tempFilePaths,
          name: 'file',
          url: config.BASE_URL + '/home/recognition',
          header: {
            token: token
          },
          success(res) {
            console.log('上传图片',res);
            // that._wsreq()
          }
        })
      },
      fail(err) {
        console.error('选择图片失败:', err)
      }
    })
  },
  recordTouchStart() {
    this._recordStart()
  },
  recordTouchEnd() {
    manager.stop()
  },
  _recordStart() {
    manager.start({
      lang: 'zh_CN'
    })
  },
  _initReco() {
    const that = this
    manager.onStop = function(res) {
      console.log("record file path", res.tempFilePath)
      console.log("result", res.result)
      if (res.result === '') {
        wx.showModal({
          title: '提示',
          content: '没有听清，请再说一次~',
          showCancel: false,
        });
        return;
      }
      var text = res.result;
      that.setData({
        content: text,
      });
      // 传递参数给分类页面
      wx.navigateTo({
        url: `/pages/category/category?key=${text}`,
      })
    }
    manager.onStart = function(res) {
        console.log("成功开始录音识别", res)
    }
    manager.onError = function(res) {
        console.error("error msg", res.msg)
    }
  },
  choosePic() {
    wx.chooseMedia({
      count: 1,
      //sizeType所选的图片的尺寸，original原图，compressed压缩图
      sizeType: ['original', 'compressed'],
      success: (e) => {
        console.log(e);
      }
    })
  },
  _wsreq() {
    const that = this
    const userInfo = wx.getStorageSync('userInfo')
    wx.connectSocket({
      url: config.WS_URL + `/ws/${userInfo.id}`,
      success: (res) => {
        console.log("连接成功：" + res);
        that.setupSocketEvents()
      },
      fail: (res) => {
        console.log("连接失败" + res);
      }
    })
  },
  // websocket事件管理
  setupSocketEvents() {
    const that = this;
    // 监听连接打开事件
    wx.onSocketOpen(function(res) {
      console.log('WebSocket 连接已打开', res);
      // 连接成功后可以发送认证消息
    });
    // 监听收到消息事件
    wx.onSocketMessage(function(res) {
      if (that.data.isFalse) return
      Toast.clear()
      console.log('收到服务器消息:', res.data);
      // 处理消息逻辑
      const data = JSON.parse(res.data);
      // that.handleMessage(data);
      console.log(data);
      // 处理data
      const result = data.map(item => {
        // 使用正则表达式匹配 category 中的数字
        const match = item.category.match(/\d+/);
        if (match) {
          // 如果匹配到数字，提取第一个匹配结果并覆盖 category 字段
          item.category = match[0];
        }
        return item;
      });
      
      console.log(result);
      that.setData({
        picRecordRes: result
      })
      // 打开蒙层
      that.setData({
        show: true
      })
    });
    // 监听错误事件
    wx.onSocketError(function(err) {
      console.error('WebSocket 错误:', err);
    });
    // 监听连接关闭事件
    wx.onSocketClose(function(res) {
      console.log('WebSocket 连接已关闭', res);
    });
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  getSwiperList() {
    wx.request({
      url: 'url',
      method: 'GET',
      success: (res) => {
        this.setData({
          swiperList: res.data
        })
      }
    })
  },
  async _getCategoryImg() {
    const token = wx.getStorageSync('token')
    const res = await wx.p.request({
      url: config.BASE_URL+`/home/type`,
      method: 'GET',
      header: {
        token: token
      }
    })
    const list = res.data.data
    list.map(element => {
      element.image = replaceBaseUrl(config.PIC_URL,element.image)
    });
    console.log(list);
    this.setData({
      gridList: [...list]
    })
    this.setData({
      'store.categoryImg': list
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this._getSwperList()
    this._initReco()
    this._getCategoryImg()
    this._wsreq()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})